// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
/**
 * 
 * @param {活动日期 yy-MM-dd    } activateDate 
 * @param {活动类型 0-person 1-work 2-account} type 
 * @param {开始时间 } startTime 
 * @param {结束时间} endTime
 * @param {重复类型 0-once 1-day 2-everyWeek 3-month} isRepreatType 
 * @param {true or fasle} needRemind  
 * @param {string} description 
 * @param {"person"|"group"} tag 
 */
async function enqueue(openid, {
    activateDate,
    type,
    startTime,
    endTime,
    isRepreatType,
    needRemind,
    description,
    tag
}) {
    return new Promise(async(resolve, reject) => {
         db.collection('schdule').add({
                data: [{
                    _openid: openid || 1,
                    schduleTime: new Date(activateDate),
                    phone:18628525985,
                    tag,
                    startTime:new Date(startTime),
                    endTime:new Date(endTime),
                    isDone: 0,
                    type,
                    isRepreatType,
                    needRemind,
                    description,
                    group:  0
                }]
            })
            .then((res) => {
                resolve("ok")
            })
            .catch(err => {
                console.log(err)
                reject(err)
            })
    })
}
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let msg = "success"
    let code = 200
    let data
    console.log(event)
    try {
        if (event.startTime <= new Date().getTime()) {
            code = 400
            throw Error("cannot be insert to schdule task table because it's startTime is older more than current time!")
        }
        let result = await enqueue(wxContext.OPENID || wxContext.FROM_OPENID || event._openid, event)
        msg=result
    } catch (err) {
        code = 400
        msg = err.message || err
    }
    return {
        code,
        data,
        msg
    }
}